from django.core.cache import cache
from django.contrib.auth import authenticate
from django.contrib.auth.models import AnonymousUser
from rest_framework.exceptions import ValidationError
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from .models import *
import random


class RegCodeSerializers(serializers.Serializer):
    mobile=serializers.RegexField(label='手机号',regex=r'^[0-9].*$',max_length=20,required=True)
    code=serializers.CharField(label='验证码',read_only=True)

    def validate(self, attrs):
        mobile=attrs['mobile']
        key=f'reg_code_by_{mobile}'

        code_len=6
        code=''.join([str(random.randint(0,9)) for i in range(code_len)])
        cache.set(key,code,600)

        attrs['code']=code
        return attrs


class NewUserSerializers(serializers.ModelSerializer):
    code=serializers.CharField(label='验证码',required=True)
    class Meta:
        model=User
        fields=('username','mobile','password','code')

    def save(self):
        self.validated_data.pop('code')
        return super().save()
    def create(self, validated_data):
        instance = User.objects.create_user(**validated_data)
        return instance

    def validate_mobile(self,value):
        #对手机号进行二次处理
        #判断手机号是否存在？
        if User.objects.filter(mobile=value).exists():
            raise ValidationError('手机号已注册')
        else:
            return value
        #1.存在，打印：
        #2.不存在：

    def validate_code(self, value):
        # 那到验证码，进行验证
        # 如果验证码通过，销毁
        mobile=self.initial_data['mobile']
        key=f'reg_code_by_{mobile}'

        code=cache.get(key)

        if not code or code != value:
            raise ValidationError('验证码无效')
        else:
            cache.delete(key)
            # cache.set(key,'') #销毁验证码,方法二
            # cache.ttl()       #销毁验证码，方法三
        return value


class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField(label='用户名',required=True)
    password = serializers.CharField(label='密码',required=True)
    token = serializers.CharField(label='Token.key',read_only=True)
    user = AnonymousUser()
    def validate(self, attrs):
        username = attrs['username']
        password = attrs['password']
        request = self.context['request']
        user = authenticate(request,username=username,password=password)

        if not user:
            raise ValidationError('用户名和密码不匹配')
        self.user = user
        token, is_create = Token.objects.get_or_create(user=user)
        attrs['token']=token.key
        return attrs


class AddressSerializer(serializers.ModelSerializer):

    class Meta:
        model = Address
        exclude = 'user',

    def save(self, **kwargs):
        request = self.context['request']
        self.validated_data['user'] =request.user
        return super().save(**kwargs)


class CheckInSerializer(serializers.ModelSerializer):

    class Meta:
        model = CheckIn
        exclude = 'user',

